<?php

namespace Admin\Model;
use Think\Model;
use \stdClass;

class MenuModel  extends Model{
	protected $tableName = 'menu';

	/**
	 * [getAllMenu 获取所有展示的菜单数据]
	 * @return [array] [description]
	 */
	public function getAllMenu( )
	{
		$where['show'] = 1;

	    $data = $this->where($where)->order('orderid asc')->select();
	    foreach( $data as $key=>$d ){
	    	$data[$key]['attr'] = unserialize($d['attr']);
	    }
	    return $data;
	}

	/**
	 * [getTree 构造树形数组]
	 * @param  [array] $menus [description]
	 * @return [array]        [description]
	 */
	public function getTree( $menus=null )
	{
		if( $menus==null ){
			$menus = $this->getAllMenu();
		}

    	$id = $level = 0;
		$menuobjs = array();
    	$tree = array();
		$notrootmenu=array();
    	foreach($menus as $menu){
	        $menuobj = new stdClass();
			$menuobj->menu = $menu;
    		$id = $menu['id'];
			$level = $menu['pid'];
			$menuobj->nodes = array();
			$menuobjs[$id] = $menuobj;
			if ( $level ) {
				$notrootmenu[] = $menuobj;
			} else {
				$tree[] = $menuobj;
			}
    	}

		foreach($notrootmenu as $menuobj){
			$menu = $menuobj->menu;
			$id = $menu['id'];
			$level = $menu['pid'];
			$menuobjs[$level]->nodes[] = $menuobj;
		}

    	return $tree;
	}
	/**
	 * [getMenu 获取菜单]
	 * @param [array] $where
	 */
	public function getMenu($where=1)
	{
		return $this->where($where)->order('orderid asc')->select();
	}
	/**
	 * [getMenu 添加菜单]
	 * @param [array] $data
	 */
	public function addMenu($data){
		return $this->data($data)->add();
	}
	/**
	 * [getMenu 添加菜单]
	 * @param [array] $where
	 * @param [array] $data
	 */
	public function updataMenu($where,$data){
		return $this->data($data)->where($where)->save();
	}
}